/**
******************************************************************************
* @file    			bsp_tim.c
* @version 			V1.0
* @date    			2024-08-21
* @brief 		    wizchip tim initialization
*
* @company  		WIZnet
* @website  		https://wiznet.io/
* @gitee            https://gitee.com/wiznet-hk
* @github           https://github.com/Wiznet/
******************************************************************************
*/

#include "bsp_tim.h"
#include "dhcp.h"
#include "w55mh32_tim.h"
#include "w55mh32_rcc.h"
#include "misc.h"

/**
 * @brief   1ms timer init
 * @param   none
 * @return  none
 */
void tim3_init(void)
{
    TIM_TimeBaseInitTypeDef tim_time_base_structure;
    NVIC_InitTypeDef        nvic_init_structure;
    RCC_ClocksTypeDef       clocks;

    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, enable); // Clock enablement
    RCC_GetClocksFreq(&clocks);

    tim_time_base_structure.TIM_Period        = 1000 - 1;                            // Automatic reloading cycle value
    tim_time_base_structure.TIM_Prescaler     = clocks.HCLK_Frequency / 1000000 - 1; // Clock frequency pre division value
    tim_time_base_structure.TIM_ClockDivision = TIM_CKD_DIV1;
    tim_time_base_structure.TIM_CounterMode   = TIM_CounterMode_Up;                  // Up counting mode
    TIM_TimeBaseInit(tim3, &tim_time_base_structure);

    TIM_ITConfig(tim3, TIM_IT_Update, ENABLE); // Enable update interrupt

    nvic_init_structure.NVIC_IRQChannel                   = tim3_irqn;
    nvic_init_structure.NVIC_IRQChannelPreemptionPriority = 0;
    nvic_init_structure.NVIC_IRQChannelSubPriority        = 3;
    nvic_init_structure.NVIC_IRQChannelCmd                = ENABLE;
    NVIC_Init(&nvic_init_structure);

    TIM_Cmd(tim3, ENABLE);
}

/**
 * @brief   1ms timer IRQ Handler
 * @param   none
 * @return  none
 */
void tim3_irq_handler(void)
{
    static unsigned int  tim3_1ms_count = 0;
    if (TIM_GetITStatus(tim3, TIM_IT_Update) != reset)
    {
        tim3_1ms_count++;
        if (tim3_1ms_count >= 1000)
        {
            DHCP_time_handler();
            tim3_1ms_count = 0;
        }
        TIM_ClearITPendingBit(tim3, TIM_IT_Update);
    }
}
